import { ref, reactive, computed } from 'vue'
import { defineStore } from 'pinia'
import passage from '../utils/passage'
const access = passage('ax')

export const useUserStore = defineStore('user', () => {
  const account = reactive({
    id: 0,
    name: 'world',
    role: ''
  })
  const userinfo = ref({})

  const user = computed(() => {
    const { name } = account
    return name
  })

  //使用Promise包裹axios对象，更换resolve的参数
  const login = (params) => {
    return new Promise((resolve) => {
      access.sending('login', params).then(
        (res) => {
          if (res.type == 'success') {
            account.id = res.data.id
            account.name = res.data.name
            account.role = res.data.role
            //localStorage.setItem('token', res.data.token)
            resolve(true)
          } else resolve(false)
        },
        (reason) => {
          console.log(reason)
        }
      )
    })
  }
  const save = async (url) => {
    const res = await access.sending(url, userinfo.value)
    if (res.type == 'success' && url === 'regist') {
      account.id = res.data.id
      account.name = res.data.name
      userinfo.value.id = res.data.id
    }
    return res
  }
  //使用callback，替代resolve及参数
  const editInfo = (callback) => {
    let promise = access.sending('edit', userinfo.value)
    promise.then((res) => {
      if (res.type == 'success') {
        console.log(res)
        callback(true)
      }
    })
    return promise
  }
  //用异步函数的方式承接Promise对象，返回Promise对象
  const getInfo = async () => {
    const res = await access.sending('info', { id: account.id })
    if (res.type == 'success') {
      userinfo.value = res.data
    }
    return res
  }
  const logout = () => {
    account.id = 0
    account.name = ''
    account.role = ''
  }
  const unlink = () => {
    access.closing()
  }

  return { account, user, login, userinfo, getInfo, editInfo, logout, unlink, save }
})
